<?php
namespace app\common\service\user;



use app\admin\model\user\User;
use app\admin\model\user\UserBill;
use app\admin\model\user\UserSignDeploy;
use app\common\service\BaseService;
use app\admin\model\user\UserSign as Sign;

class UserSign extends BaseService
{
    /**
     * Author:Yingbo Sun
     * 签到
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function sign($uid)
    {
        $user = User::where('id',$uid)->find();
        if ($user->isEmpty()){
            return self::fail('该用户不存在');
        }
        if ($user->status != 1){
            return self::fail('该用户已禁用');
        }
        $getSignDeploy = UserSignDeploy::select();
        if ($getSignDeploy->isEmpty()){
            return self::fail('请先配置签到天数');
        }
        //获取前一天时间时间戳
        $yesterday = strtotime(date('Y-m-d 00:00:00',strtotime('-1days')));
        $yesterdays = strtotime(date('Y-m-d 23:59:59',strtotime('-1days')));
        //获取今天时间戳
        $today = strtotime(date('Y-m-d 00:00:00'));
        $todays = strtotime(date('Y-m-d 23:59:59'));
        $wheres[] = ['uid','=',$uid];
        $wheres[] = ['add_time','between',[$today,$todays]];
        //查询今天是否签到
        $todaySign = Sign::where($wheres)->find();
        if (!empty($todaySign)){
            return self::fail('您今天已经签到了');
        }
        $where[] = ['uid','=',$uid];
        $where[] = ['add_time','between',[$yesterday,$yesterdays]];
        //查询前一天签到记录
        $sign = Sign::where($where)->find();
        if ($user->sign_sum >= 7){
            $user->sign_sum = 0;
        }
        //检测昨天是否签到或该用户是否签过到
        if (empty($sign)){
            //签到回到第一天
            $user->sign_sum = 1;
        }else{
            //连续签到
            $user->sign_sum +=1;
        }
        //签到积分
        $integral = 0;
        foreach ($getSignDeploy as $k=>$v){
            if ($v->sign_num == $user->sign_sum){
                $integral = $v->earn_point;
                break;
            }
        }
        $number = bcadd($integral,$user->integral,0);
        $user->integral = $number;
        $res = $user->save();
        //添加签到记录
        $res1 = Sign::setSignData($uid,'签到奖励',$integral,$number);
        if ($res1 && $res){
            return self::success('签到成功');
        }else{
            return self::fail('签到失败');
        }
    }

    /**
     * Author:Yingbo Sun
     * 补签
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function retroactive($uid)
    {
        if (empty($uid)){
            return self::fail('参数错误');
        }
        $user = User::where('id',$uid)->find();
        //签到需要积分
        $integral = 30;
        if ($user->integral < $integral){
            return self::fail('积分不足，补签失败');
        } 
        //只查询最近七天 没有签到的
        $count = 7;
        for ($i = 1; $i <= $count + 1; $i++){
            $where = [];
            //获取前一天时间时间戳
            $yesterday = strtotime(date('Y-m-d 00:00:00',strtotime("-{$i} days")));
            $yesterdays = strtotime(date('Y-m-d 23:59:59',strtotime("-{$i} days")));
            $where[] = ['uid','=',$uid];
            $where[] = ['add_time','between',[$yesterday,$yesterdays]];
            $data = Sign::where($where)->find();
            if (empty($data)){
                $sign['uid'] = $uid;
                $sign['title'] = '用户补签';
                $sign['add_time'] = $yesterdays;
                $sign['sign_time'] = date('Y-m-d',$yesterdays);
                self::beginTrans();
                try {
                    Sign::create($sign);
                    //补签记录
                    UserBill::income('用户补签',$uid,0,'integral','sign');
                    self::commitTrans();
                }catch (\Exception $e){
                    self::rollbackTrans();
                    return self::fail('补签失败');
                }
//                break;
                return self::fail('不需要补签');
            }
        }
        $signList = Sign::where('uid',$uid)->order('add_time','desc')->select();
        $signList && $signList = $signList->toArray();
        $sign_sum = 0;
        //连续签到天数
        for ($i = 1; $i <= count($signList) + 1; $i++){
            $where = [];
            //获取前一天时间时间戳.
            $yesterday = strtotime(date('Y-m-d 00:00:00',strtotime("-{$i}days")));
            $yesterdays = strtotime(date('Y-m-d 23:59:59',strtotime("-{$i}days")));
            $where[] = ['uid','=',$uid];
            $where[] = ['add_time','between',[$yesterday,$yesterdays]];
            $data = Sign::where($where)->find();
            if (empty($data)){
                //连续签到天数
                $sign_sum = $i-1;
                break;
            }
        }
        //获取今天的时间戳
        $today = strtotime(date('Y-m-d 00:00:00',time()));
        $todays = strtotime(date('Y-m-d 23:59:59',time()));
        $where = [];
        $where[] = ['uid','=',$uid];
        $where[] = ['add_time','between',[$today,$todays]];
        $sign = Sign::where($where)->find();
        //判断今天是否签到 true连续签到天数+1
        if (!empty($sign)){
            $sign_sum += 1;
        }
        $user->sign_sum = $sign_sum;
        $user->integral -= $integral;
        $res = $user->save();
        if ($res){
            return self::success('补签成功');
        }else{
            return self::fail('补签失败');
        }
    }

    /**
     * Author:Yingbo Sun
     * 签到配置列表
     * @param $page
     * @param $limit
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function list($page, $limit, $where)
    {
        $count = UserSignDeploy::where($where)
            ->count();
        $list = UserSignDeploy::where($where)
            ->page($page, $limit)
            ->order('sort','desc')
            ->select();
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $list,
        ];
        return $data;
    }
    /**
     * Author:Yingbo Sun
     * 判断今天是否签到
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isSign($uid)
    {
        if (empty($uid)){
            return self::fail('参数错误');
        }
        $today = date('Y-m-d');
        $where[] = ['uid','=',$uid];
        $where[] = ['sign_time','=',$today];
        $data = Sign::where($where)->find();
        $user = User::where('id',$uid)->find();
        $res['sign_sum'] = $user->sign_sum;
        if ($data){
            $res['SigninStatus'] = 1;
            return self::success('已经签到了',$res);
        }else{
            if ($res['sign_sum'] == 7){
                $res['sign_sum'] = 0;
            }
            $res['SigninStatus'] = 0;
            return self::success('今天还未签到',$res);

        }
    }





}